# 导包
import pymysql

# 初始化连接对象和游标对象
connect = None
cursor = None
try:
    # 创建链接
    connect = pymysql.connect(host='localhost', port=3306, user='root', password='root', database='books',
                              autocommit=False)
    # 创建游标
    cursor = connect.cursor()
    # 执行sql
    sql = 'insert into t_book (id, title, pub_date) values(4, "西游记", "1986-01-01")'
    cursor.execute(sql)
    print(cursor.rowcount)
    # raise Exception("不好意思我错了")
    sql = 'insert into t_hero (id, name, gender, book_id) values(6, "孙悟空", 1, 4)'
    cursor.execute(sql)
    print(cursor.rowcount)
    # 提交事务
    connect.commit()
except Exception as e:
    # 回滚事务
    connect.rollback()
    # 打印错误信息
    print(e)
finally:
    # 关闭游标
    if cursor:
        cursor.close()
    # 关闭链接
    if cursor:
        connect.close()
